package com.demo.cloud.security.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.demo.cloud.security.gateway.util.EncryptUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AuthFilter extends ZuulFilter {

    /**
     * 在请求前进行拦截
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 微服务需要当前的权限和身份信息。
     * 解析成json格式放在请求头中
     * @return
     */
    @Override
    public Object run() {

        // 获取当前用户的身份信息
        RequestContext ctx = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)){
            // 无token访问网关内资源情况，目前仅有uaa服务直接暴露
            return null;
        }

        // 获取出当前用户的权限信息
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

        Object principal = null;
        if (userAuthentication != null){
            principal = userAuthentication.getPrincipal();
        }

        // 把身份信息和权限信息放在JSON中，加入到HTTP header中
        List<String> authorities = new ArrayList<>();
        oAuth2Authentication.getAuthorities().forEach(s -> authorities.add(s.getAuthority()));
        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String, Object> jsonToken = new HashMap<>(requestParameters);

        if (userAuthentication != null){
            jsonToken.put("principal", principal);
            jsonToken.put("authorities", authorities);
        }
        // 转发给微服务
        ctx.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));

        return null;
    }
}
